<?php
include_once("Fn.class.php");
if(!class_exists('t')) {
    class t
    {
        //定义常量、变量
        const SECRET_KEY = '@4!@#$%@';
        public $cn;
        private $hn;
        private $dn;
        private $zd;
        private $zd1;
        private $zd2;
        private $zd3;
        private $key;
        private $tn;
        private $isautoadd;
        private $ku;
        private $lxupdates = 0; //连续update数
        private $maxlxupdates = 300; //最大连续修改数
        private $fields;
        public $sqlc;
        public $sql;
        protected $parentpath = "";
        public $getlastsql;


        //构造函数,入口函数
        function __construct($hn, $username, $password, $dn = "", $tn = "")
        {
            $this->set($hn, $username, $password, $dn, $tn);
        }

        public function set($hn, $username, $password, $dn = "", $tn = "")
        {

            $this->hn = $hn;
            $this->cn = new mysqli($hn, $username, $password, $dn);

            self::setutf8();
            if ($dn != "") {
                $this->dn = $dn;
                //print_r($dn."\r\n".$username."\r\n".$password);exit;
                mysqli_select_db($this->cn, $dn) or die("error9: " . mysqli_error($this->cn));
            }

            if ($tn != "") {
                $this->tn = $tn;
            }
        }

        public function setmaxlxupdates($value)
        {
            if ($value >= 0) {
                $this->maxlxupdates = $value;
            }
        }

        public function connect($hn, $username, $password, $dn = "")
        {
            if ($dn) $this->dn = $dn;
            self::set($hn, $username, $password);
            self::setutf8();
        }

        public function select_db($dn)
        {
            $this->dn = $dn;
            mysqli_select_db($this->cn, $dn) or die("error: " . mysqli_error($this->cn));
        }

        public function selectdb($dn)
        {
            $this->dn = $dn;
            mysqli_select_db($this->cn, $dn) or die("error: " . mysqli_error($this->cn));
        }

        public function selecttb($tn)
        {
            $this->tn = $tn;
        }

        public function getzd($tn = "")
        {
            if ($tn != "") $this->tn = $tn;
            $this->getkey($this->tn);
            $return = join(",", $this->zd);
            return $return;
        }

        public function setutf8()
        {
            mysqli_query($this->cn, "set character set 'utf8'");
            mysqli_query($this->cn, "set names 'utf8'");
            mysqli_query($this->cn, "set GLOBAL read_only=false");
        }

        public function setgb2312()
        {
            mysqli_query($this->cn,"set character set 'GB2312'");
            mysqli_query($this->cn,"set names 'GB2312'");
        }

        public function sql($sql, $bug = 0)
        {
            mysqli_select_db($this->cn, $this->dn); // or die("error: ". mysqli_error())
            $this->getlastsql=$sql;
            $ku = mysqli_query($this->cn, $sql);
            if ($bug && mysqli_error($this->cn) != "") echo $sql . "\r\n" . mysqli_error($this->cn);
            $this->ku = $ku;
            return $ku;
        }

        public function execute($sql, $bug = 0)
        {
            mysqli_select_db($this->cn, $this->dn);
            mysqli_query($this->cn, $sql) or die($sql . mysqli_error($this->cn));
            $this->sql = $sql;
            $this->getlastsql=$sql;
            if ($bug || mysqli_error($this->cn) != "") $this->sql .= "\r\n error:" . mysqli_error($this->cn) . "\r\n\r\n" . self::goodsql($sql);
        }

        public function sqlku($sql, $bug = 0)
        {
            mysqli_select_db($this->cn, $this->dn);
            $this->ku = $ku = mysqli_query($this->cn, $sql);
            if ($bug && mysqli_error($this->cn) != "") echo "\r\n" . mysqli_error($this->cn);
            return $ku;
        }

        public function sqlkuarray($sql, $bug = 0)
        {
            mysqli_select_db($this->cn, $this->dn);
            $this->ku = $ku = mysqli_query($this->cn, $sql);
            if ($bug && mysqli_error($this->cn) != "") echo "\r\n" . mysqli_error($this->cn);
            $array = array();
            //if(mysqli_num_rows($ku)<=0) return array();
            while ($rs = mysqli_fetch_array($ku)) {
                $array[] = $rs;
            }

            $newarr = array();
            for ($i = 0; $i < count($array); $i++) {
                foreach ($array[$i] as $k => $v) {
                    if (is_int($k)) continue;
                    $newarr[$i][$k] = $v;
                }
            }

            if (count($newarr[0]) == 1) {
                $newarrtemp = $newarr;
                $newarr = array();
                for ($i = 0; $i < count($newarrtemp); $i++) {
                    foreach ($newarrtemp[$i] as $k => $v) {
                        $newarr[] = $v;
                    }
                }
            }
            //if (count($newarr) == 1) $newarr = current($newarr);
            return $newarr;
        }

        public function sqlone($sql, $bug = 0)
        {
            mysqli_select_db($this->cn, $this->dn);
            $this->getlastsql=$sql;
            $this->ku = $ku = mysqli_query($this->cn, $sql);
            $this->sql = $sql;
            //if ($bug || mysqli_error() != "") $this->sql .= "\r\n" . mysqli_error();
            $r = @mysqli_fetch_array($ku);
            return $r;
        }

        public function sqlvalue($sql, $bug = 0)
        {
            mysqli_select_db($this->cn, $this->dn);
            $this->getlastsql=$sql;
            $this->ku = $ku = mysqli_query($this->cn, $sql);
            if ($bug || mysqli_error($this->cn) != "") $this->sql .= "\r\n" . mysqli_error($this->cn);
            if (@mysqli_num_rows($ku) > 0) {
                $array = @mysqli_fetch_array($ku);
                $newarr = array();

                if (is_array($array[0])) {
                    for ($i = 0; $i < count($array); $i++) {
                        foreach ($array[$i] as $k => $v) {
                            if (is_int($k)) continue;
                            $newarr[$i][$k] = $v;
                        }
                    }
                } else {
                    foreach ($array as $k => $v) {
                        if (is_int($k)) continue;
                        $newarr[] = $v;
                    }
                }

                if (is_array($newarr[0])) {
                    $newarrtemp = $newarr;
                    $newarr = array();
                    for ($i = 0; $i < count($newarrtemp); $i++) {
                        foreach ($newarrtemp[$i] as $k => $v) {
                            $newarr[] = $v;
                        }
                    }
                }
                if (count($newarr) == 1) $newarr = current($newarr);
            } else {
                $newarr = 0;
            }
            $return = ($newarr == 0) ? 0 : $newarr;
            $this->sql .= "\r\n" . $return;
            return $return;
        }


        public function writetobd()
        {
            $cn2 = mssql_connect("127.0.0.1", "sa", "159456");
            mssql_select_db("yangzs", $cn2);
            if ($this->hn) mssql_query("update copy set text = '" . $this->hn . "' where dh = 'myhn'", $cn2);
            if ($this->dn) mssql_query("update copy set text = '" . $this->dn . "' where dh = 'mydn'", $cn2);
            if ($this->tn) {
                self::getkey($this->tn);
                mssql_query("update copy set text = '" . $this->tn . "' where dh = 'mytn'", $cn2);
                mssql_query("update copy set text = '" . $this->zd1 . "' where dh = 'zd1'", $cn2);
                mssql_query("update copy set text = '" . $this->zd2 . "' where dh = 'zd2'", $cn2);
                mssql_query("update copy set text = '" . $this->zd3 . "' where dh = 'zd3'", $cn2);
                mssql_query("update copy set text = '" . $this->key . "' where dh = 'key'", $cn2);
                mssql_query("update copy set text = '" . $this->isautoadd . "' where dh = 'autoadd' or dh = 'isautoadd'", $cn2);
                mssql_query("update copy set text = '" . join(",", $this->zd) . "' where dh = 'zd'", $cn2);
                $sql = "update copy set text = '" . $this->zd2 . "=''\$" . $this->zd2 . "''," . $this->zd3 . "=''\$" . $this->zd3 . "''' where dh = 'where'";
                mssql_query($sql, $cn2);
            }
        }

        public function settn($tn)
        {
            $this->tn = $tn;
            self::writetobd();
        }

        public function getkey($tn)
        {

            $zd = array();
            $this->fields();
            mysqli_select_db($this->cn, $this->dn) or die("error: " . mysqli_error($this->cn));
            $result = $this->sql("select * from $tn limit 0,1",1);
            $result=mysqli_fetch_fields($result);
            for ($i = 0; $i < count($result); $i++) {
                $this->zd1 = $result[0]->name;
                $this->zd2 = $result[1]->name;
                $this->zd3 = $result[2]->name;

                if (preg_match("/primary_key|PRI/Uisx",$this->fields[$result[$i]->name][key]) ) {
                    if (preg_match("/auto_increment/Uisx", $this->fields[$result[$i]->name][auto])) {
                        $this->isautoadd = 1;
                    } else {
                        $this->isautoadd = 0;
                    }
                    $return = $result[$i]->name;
                    $this->key = $return;
                }
                $zd[] = $result[$i]->name;
            }
            $this->zd = $zd;

            return $this->key;
        }


        public function fields()
        {
            global $t;
            if (!isset($tn)) $tn = $this->tn;
            mysqli_select_db($this->cn, $this->dn) or die("error: " . mysqli_error($this->cn));
            $result = $this->sql("SHOW FULL FIELDS FROM $tn", 1);
            $arr = array();
            while ($rs = mysqli_fetch_array($result)) {
                $arr[$rs['Field']]['type'] = $rs['Type'];
                $arr[$rs['Field']]['key'] = $rs['Key'];
                $arr[$rs['Field']]['auto'] = $rs['Extra'];
                $arr[$rs['Field']]['null'] = $rs['Null'];
                $arr[$rs['Field']]['default'] = (preg_match("/int/ ", $arr[$rs['Field']]['type'])) ? 0 : $rs['Default'];
                $arr[$rs['Field']]['default'] = (preg_match("/float\([0-9]+\,([0-9]+)\)/x", $arr[$rs['Field']]['type'], $nn)) ? "0." . str_repeat("0", $nn[1]) : $arr[$rs['Field']]['default'];
            }
            $this->fields = $arr;
            return $arr;
        }

        public function rkarray($tablen, $zd, $where, $param = array(), $data)
        {
            foreach ($data as $key => $v) {
                $return = self::rk($tablen, $zd, $where, $param, $v);
                if ($return == "break") break;
            }
        }

        public function listku()
        {
            $kutemp = $this->ku;
            echo "\r\n";
            while ($rs = mysqli_fetch_array($kutemp)) {
                for ($i = 0; $i < mysqli_num_fields($kutemp); $i++) {
                    echo "[" . preg_replace(" / (\r | \n) +/m", " ", trim($rs[$i])) . "]\t    ";
                }
                echo "\r\n";
            }
        }


        public function rk($tablen, $zd, $where, $param = array(), $data = array())
        {
            $this->tn = $tablen;
            $this->getkey($this->tn);
            $pczd = $urlreplace = $urlreplace2 = $urlreplace3 = "";
            extract($param);
            self::mextract($data);
            $zdarr =is_array($zd)?$zd:preg_split("/\s*,\s*/x", $zd);
            $pczd = is_array($pczd)?$pczd:preg_split("/\s*,\s*/x", $pczd);
            $qzsxarray = (isset($qzsxarray)) ? $qzsxarray : array();
            if (!empty($keyarray)) {
                foreach ($keyarray as $k2 => $v2) {
                    $GLOBALS[$k2] = $GLOBALS[$v2]; //keyarray 的参数例子 'id'=>'xxid' 非  'id'=>'$xxid'
                }
            }


            $fields = $this->fields;
            $fieldsarray = array_keys($fields);
            if(!function_exists("cbfun11")) {
                function cbfun11($nn)
                {
                    return str_replace("'", "''", $GLOBALS[$nn[1]]);
                }
            }
            $where = preg_replace_callback(" /\\\$([a-zA-Z0-9_]+)/isx", "cbfun11", $where);
            $sql = "select * from $tablen limit 0,1";
            $r = self::sqlone($sql);
            $sql0 = $sql2 = $sql3 = "";
            foreach ($fieldsarray as $k => $fd) {

                if ($zd != "" && !in_array(trim($fd), $zdarr) || in_array($fd, $pczd)) {
                    continue;
                }

                $this->fields[$fd]['default'] = (preg_match("/int|float/", $this->fields[$fd]['type']) && $this->fields[$fd]['null'] == "NO") ? 0 : $this->fields[$fd]['default'];
                $GLOBALS[$fd] = (!isset($GLOBALS[$fd]) && preg_match("/int|float/", $this->fields[$fd]['type'])) ? 0 : $GLOBALS[$fd];
                $GLOBALS[$fd] = ($GLOBALS[$fd] == "" && preg_match("/int|float/", $this->fields[$fd]['type'])) ? 0 : $GLOBALS[$fd];
                $GLOBALS[$fd] = (($GLOBALS[$fd] == "" || !isset($GLOBALS[$fd])) && $this->fields[$fd]['type'] == "date") ? date("Y-m-d") : $GLOBALS[$fd];
                $GLOBALS[$fd] = (($GLOBALS[$fd] == "" || !isset($GLOBALS[$fd])) && $this->fields[$fd]['type'] == "datetime") ? date("Y-m-d H:i:s") : $GLOBALS[$fd];
                if ($this->fields[$fd]['key'] != "PRI" || $this->fields[$fd]['auto'] != "auto_increment") {
                    if ($this->fields[$fd]['null'] == "NO" && isset($this->fields[$fd]['default']) && trim($GLOBALS[$fd]) == "") {
                        $sql0 .= "`$fd`,";
                        $sql2 .= "'" . self::clf($this->fields[$fd]['default']) . "',";
                    } else {
                        $sql0 .= "`$fd`,";
                        $sql2 .= "'" . self::clf($GLOBALS[$fd]) . "',";
                    }
                }


                if ((!Fn::isnull($GLOBALS[$fd]) || isset($this->fields[$fd]['default']))) {
                    $GLOBALS[$fd] = (trim($GLOBALS[$fd]) == 'null') ? "" : $GLOBALS[$fd];
                    if ($this->fields[$fd]['key'] != "PRI" || $this->fields[$fd]['auto'] != "auto_increment") {
                        if ($this->fields[$fd]['null'] == "NO" && isset($this->fields[$fd]['default']) && trim($GLOBALS[$fd]) == "") {
                            $sql3 .= "`$fd`='" . self::clf($this->fields[$fd]['default']) . "',";
                        } else {
                            $sql3 .= "`$fd`='" . self::clf($GLOBALS[$fd]) . "',";
                        }
                    }
                }
            }

            $sql0 = substr($sql0, 0, -1);
            $sql2 = substr($sql2, 0, -1);
            $sql3 = substr($sql3, 0, -1);
            mysqli_select_db($this->cn, $this->dn);

            $sql = "select * from $tablen where $where $orderby limit 0,1";
            $r = self::sqlone($sql);
            $this->sqlc = $sql;

            if ($r[$this->key] > 0) {
                if ($sql3 != "") {
                    $sql = "update $tablen set $sql3 where " . $this->key . "=" . $r[$this->key];
                    //echo "\r\n<br>" . $sql;
                    $this->getlastsql=$sql;
                    $this->execute($sql);
                    $this->lxupdates++;
                    if ($this->lxupdates >= $this->maxlxupdates) {
                        $this->lxupdates = 0;
                        return "break";
                    }
                }
                $return = $r[$this->key];
            } elseif ($insert == 1) {
                if ($sql0 != "" && $sql2 != "") {
                    $sql = "insert into $tablen ($sql0) values ($sql2)";
                    //echo "\r\n<br>" . $sql;
                    $this->getlastsql=$sql;
                    $this->execute($sql, $bug);
                    $sql2 = "select " . $this->key . " from " . $this->tn . " order by " . $this->key . " desc limit 0,1";
                    $r3 = self::sqlone($sql2);
                    $return = $r3[$this->key];
                    $this->sql = $this->sql . "\r\n" . self::goodsql($sql) . "\r\n" . $return;
                } else {
                    $return = 0;
                }
                $this->lxupdates = 0;
            } else {
                $return = 0;
            }

            //if ($backfun != "") {
            //$backfun($return);
            //}
            //echo $sql;
            //r($sql);
            //if ($bug) echo "\r\n返回:" . $return . "\r\n";
            return $return;

        }


        //静态方法
        static public function mextract($arr)
        {
            if (!empty($arr) && is_array($arr)) {
                foreach ($arr as $key => $value) {
                    $GLOBALS[$key] = $value;
                }
            }
        }

        static public function goodsql($sql)
        {
            if (preg_match("/(insert\s+into.*)\((.*)\)\s*values\s*\((.*)\'\)/Uisx", $sql, $nn)) {
                $s = $nn[1] . "\r\n(";
                $k = preg_split("/\,/", $nn[2]);
                $v = preg_split("/\'\,\'/", $nn[3]);
                for ($i = 0; $i < count($k); $i++) {
                    $s .= $k[$i] . "=>" . $v[$i] . "\r\n";
                }
                $s .= "\r\n)";
                return $s;
            }
            return $sql;
        }

        function clf($str)
        {
            if (!get_magic_quotes_gpc()) {
                $str = addslashes($str);
            }
            return $str;
        }

    }

    function getlastsql(){
        return $this->getlastsql;
    }
}
?>